package com.ian.tag.array;

import java.util.HashSet;



public class SubarraysWithKDistinct {

    public int subarraysWithKDistinct(int[] A, int K) {

         return withsct(A,K) -withsct(A,K-1);
        }

    private int withsct(int[] a, int k) {

        int size  =a.length;
        int[] free = new int[size+1];

        int left = 0,right = 0,count = 0,res = 0;

        while(right< size){

              if (free[a[right]] == 0){
                  count++;
              }
              free[a[right]]++;
              right++;

              while(count>k){
                   free[a[left]]--;
                   if (free[a[left]]==0) {
                       count--;
                   }
                   left++;
              }
            res += right-left;
        }

        return  res;
    }


}



